package top.zhaoyuliu.logbook.server.connect.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import top.zhaoyuliu.logbook.client.builder.ParameterLbBuilder;
import top.zhaoyuliu.logbook.client.connect.packet.PacketBuilder;
import top.zhaoyuliu.logbook.client.connect.packet.PacketType;
import top.zhaoyuliu.logbook.server.connect.client.ClientStart;

/**
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: ParamService.java
 * @Prject: logbook-server
 * @Package: top.zhaoyuliu.logbook.server.connect.service
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月23日 下午1:37:46
 * @version: V1.0
 */
@Service
public class ParamService extends TaskService implements DataService {

	@Autowired
	private ClientStart clientStart;

	@Override
	public Byte getType() {
		return PacketType.PARA;
	}

	@Override
	public void handler(String data, ChannelContext channelContext) {
		List<ParameterLbBuilder> list = JSONUtil.isJson(data)
				? JSONUtil.toList(JSONUtil.parseArray(data), ParameterLbBuilder.class)
				: null;
		if (CollectionUtil.isNotEmpty(list)) {
			String node = handlerTask(clientStart);
			if (StrUtil.isNotBlank(node)) {
				Tio.send(clientStart.getNodeChannelContext().get(node),
						new PacketBuilder().setBody(list).setType(getType()).build());
			} else {
				clientStart.getParaQueue().addAll(list);
				clientStart.getTaskNum().addAndGet(list.size());
				clientStart.getParaQueueQueuesemaphore().release();
			}
		}
	}

}
